package com.atguigu.util;

import com.atguigu.bean.TableProcess;
import com.atguigu.common.Constant;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 任何JDBC框架的任何查询语句
 * <p>
 * select count(*) from t;                     单行单列
 * select * from t where id ='xx'; id为主键     单行多列
 * select count(*) from t group by dept_id;    多行单列
 * select * from t;                            多行多列
 * <p>
 * id name sex
 * 10 zs   m
 * 11 ls   f
 * 12 ww   m
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean isUnderScoreToCamel) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {

        ArrayList<T> list = new ArrayList<>();

        //查询
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历封装T对象放入集合  行遍历
        while (resultSet.next()) {

            //创建T对象
            T t = clz.newInstance();

            for (int i = 1; i < columnCount + 1; i++) {   //列遍历
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(i);
                if (isUnderScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }
                //给T对象属性赋值
                BeanUtils.setProperty(t, columnName, value);
            }
            //将T对象放入集合
            list.add(t);
        }

        //释放资源
        resultSet.close();
        preparedStatement.close();

        return list;
    }

    public static void main(String[] args) throws Exception {

        Connection connection = DriverManager.getConnection(Constant.MYSQL_URL, "root", "000000");

        List<TableProcess> queryList = queryList(connection, "select * from `gmall-230524-config`.table_process", TableProcess.class, true);
        for (TableProcess jsonObject : queryList) {
            System.out.println(jsonObject);
        }

        connection.close();

    }
}
